package com.example.filetest;


import java.io.File;
import java.util.HashMap;
import java.util.Map;

/*
 *
 * 统计文件夹内文件个数
 *
 * */
public class Test14 {
    public static void main(String[] args) {

        File file = new File("D:\\27162\\Desktop\\大二");
        HashMap<String, Integer> hm = new HashMap<>();
        if (file.exists()) hm = countFile(file);
        System.out.println(hm);
    }

    public static HashMap<String, Integer> countFile(File file) {
        HashMap<String, Integer> hm = new HashMap<>();
        File[] files = file.listFiles();

        for (File f : files) {
            String[] split = f.getName().split("\\.");

            if (split.length >= 2) {
                //当前文件夹文件各种类型文件个数
                String key = split[split.length - 1];
                if (hm.containsKey(key)) {
                    int value = hm.get(key);
                    value++;
                    hm.put(key, value);
                } else hm.put(key, 1);
            } else {
                //文件夹中文件夹中各种类型文件夹个数中文件个数
                HashMap<String, Integer> sonhm = countFile(f);
                for (Map.Entry<String, Integer> entry : sonhm.entrySet()) {
                    if (hm.containsKey(entry.getKey())) {
                        int i = hm.get(entry.getKey());
                        i += entry.getValue();
                        hm.put(entry.getKey(), i);
                    } else {
                        hm.put(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
        return hm;
    }

}
